<template>
  <view>
    <!-- 关于map标签: 谷歌地图使用 wgs84 坐标，其他地图使用 gcj02 坐标，用错坐标类型会显示偏移。（tis：微信小程序/h5使用高德地图） -->
    <map
      :style="{ width: width, height: height }"
      :latitude="viewCenterPoint.latitude"
      :longitude="viewCenterPoint.longitude"
      :markers="markers"
      :polyline="polyline"
      :scale="scale"
      v-if="isShowReady"
    >
    </map>
  </view>
</template>

<script>
import Config from './lib/config.js'
import amapFile from './lib/amap-uni.js'
import { watch } from 'vue'
export default {
  data() {
    return {
      markers: [],
      polyline: [],
      viewCenterPoint: {},
      defaultConfig: {
        showMarks: true,
        lineColor: '#0606ff', //路径颜色
        lineWidth: 4, //路径宽度
        startImage: './image/start.png',
        wayImage: './image/passing_points.png',
        endImage: './image/end.png'
      },
      isShowReady: false
    }
  },
  props: {
    scale: {
      type: Number,
      default: 16
    },
    width: {
      type: String,
      default: '750rpx'
    },
    height: {
      type: String,
      default: '100vh'
    },
    longitude: {
      type: Number
    },
    latitude: {
      type: Number
    },
    startPoi: {
      type: String
    },
    wayPoi: {
      type: String
    },
    endPoi: {
      type: String
    },
    Config: {
      type: Object,
      default: function () {
        return {}
      }
    },
    customMarker: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  created() {
    const that = this
    watch(
      () => [this.longitude, this.latitude, this.startPoi, this.wayPoi, this.endPoi],
      (obj) => this.update()
    )
  },
  methods: {
    // 组件主逻辑
    update() {
      let that = this
      // 设置初始点
      Object.assign(this.Config, this.defaultConfig)
      this.viewCenterPoint.latitude = this.latitude
      this.viewCenterPoint.longitude = this.longitude
      // 当没有设置初始化点时，使用起点作为初始点
      if (this.latitude == null || this.longitude == null) {
        let startPoints = this.startPoi.split(',')
        this.viewCenterPoint.longitude = parseFloat(startPoints[0])
        this.viewCenterPoint.latitude = parseFloat(startPoints[1])
      }
      // 检查数据必要性
      if (isNaN(this.viewCenterPoint.longitude) || isNaN(this.viewCenterPoint.latitude)) return
      this.isShowReady = true
      // 标记点
      if (this.Config.showMarks) {
        this.setMarkers(this.startPoi, this.endPoi, this.wayPoi, (res) => {
          // 将起始点、途经点、终点 -> 标记点
          console.log('[起点-途经点-终点]标记数据：', this.markers)
          this.markers.push(...res)
        })
      }
      // 导航线
      this.getDrivingRoute(this.startPoi, this.endPoi, this.wayPoi, (res) => {
        console.log('导航线-点集：', res)
        that.polyline.push(res)
      })
    },
    // 主要是为了获取导航线
    getDrivingRoute(start, end, _waypoints, successResultConsumer, fail) {
      console.log(Config.GAODE_KEY)
      let that = this
      var myAmapFun = new amapFile.AMapWX({
        key: Config.GAODE_KEY
      })
      myAmapFun.getDrivingRoute({
        origin: start,
        destination: end,
        waypoints: _waypoints,
        success: function (data) {
          var points = []
          if (data.paths && data.paths[0] && data.paths[0].steps) {
            var steps = data.paths[0].steps
            for (var i = 0; i < steps.length; i++) {
              var poLen = steps[i].polyline.split(';')
              for (var j = 0; j < poLen.length; j++) {
                points.push({
                  longitude: parseFloat(poLen[j].split(',')[0]),
                  latitude: parseFloat(poLen[j].split(',')[1])
                })
              }
            }
          }
          // 这个返回结果就是对应的路线坐标,其他属性页面自己配置,请参照uniapp地图组件一章节
          // https://uniapp.dcloud.io/component/map
          successResultConsumer({
            points: points,
            color: that.Config.lineColor,
            width: that.Config.lineWidth
          })
        },
        fail: function (info) {
          // 如果请求失败，好像不到这里，可以看网络请求。错误码及解释：https://lbs.amap.com/api/wx/reference/errorcode
          fail(info)
        }
      })
    },
    // marker自定义混合
    markerMix(point) {
      for (let cm of this.customMarker) {
        if (cm.longitude === point.longitude && cm.latitude === point.latitude) {
          return Object.assign(point, cm)
        }
      }
      return point
    },
    // 根据输入的起始点、途经点、终点数据转为若干标记点
    setMarkers(startpoi, endpoi, waypoints, success) {
      let markers = []

      //起点
      let start = this.markerMix({
        iconPath: this.Config.startImage,
        id: 0,
        longitude: parseFloat(startpoi.split(',')[0]),
        latitude: parseFloat(startpoi.split(',')[1]),
        width: 25,
        height: 25
      })
      markers.push(start)
      //终点
      let end = this.markerMix({
        iconPath: this.Config.endImage,
        id: 1,
        longitude: parseFloat(endpoi.split(',')[0]),
        latitude: parseFloat(endpoi.split(',')[1]),
        width: 25,
        height: 25
      })
      markers.push(end)
      //途经点,先将其分隔成为数组
      let _waypoints = waypoints.split(';')
      for (let i = 0, _len = _waypoints.length; i < _len; i++) {
        if (_waypoints[i] == null || (_waypoints[i] + '').trim() === '' || !(_waypoints[i] + '').includes(',')) continue

        let point = this.markerMix({
          iconPath: this.Config.wayImage,
          id: i + 2,
          longitude: parseFloat(_waypoints[i].split(',')[0]),
          latitude: parseFloat(_waypoints[i].split(',')[1]),
          width: 25,
          height: 25
        })
        markers.push(point)
      }

      //统一风格为回调方式,也可以直接返回这个markers
      success(markers)
    }
  }
}
</script>

<style></style>
